package com.rabbit.service.domain.provider;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.rabbit.data.page.BaseQueryModel;
import com.rabbit.service.domain.PredictDataDomain;
import com.rabbit.service.domain.entity.PredictDataEntity;
import com.rabbit.service.domain.repo.PredictDataRepo;

@Service
public class PredictDataProvider implements PredictDataDomain{

	@Autowired
	private PredictDataRepo dao;

	@Override
	public PredictDataEntity save(PredictDataEntity entity) {
		return dao.save(entity);
	}

	@Override
	public Optional<PredictDataEntity> getById(String pk) {
		return dao.findById(pk);
	}


	@Override
	public Page<PredictDataEntity> queryPage(BaseQueryModel queryModel) throws Exception {
		List<Order> orders  = new ArrayList<Sort.Order>();
		orders.add(Sort.Order.desc("createdAt"));
		Sort sort  = Sort.by(orders);
		final Map<String, Object>  map = queryModel.castMapObjects();
		PageRequest pageable = PageRequest.of(queryModel.getPageNo(), queryModel.getPageSize(),sort);
		Specification<PredictDataEntity> specifications = new Specification<PredictDataEntity>() {
			private static final long serialVersionUID = 1L;
			@Override
			public Predicate toPredicate(Root<PredictDataEntity> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				List<Predicate> list = new ArrayList<Predicate>();
//				if (StringUtil.isNotEmpty((String)map.get("email"))) {
//					Predicate p = criteriaBuilder.like(root.get("email").as(String.class), "%"+(String)map.get("email")+"%");
//					list.add(p);
//				}
//				if (StringUtil.isNotEmpty((String)map.get("phone"))) {
//					Predicate p = criteriaBuilder.like(root.get("phone").as(String.class), "%"+(String)map.get("phone")+"%");
//					list.add(p);
//				}
//				if (StringUtil.isNotEmpty((String)map.get("loginId"))) {
//					Predicate p = criteriaBuilder.like(root.get("loginId").as(String.class), "%"+(String)map.get("loginId")+"%");
//					list.add(p);
//				}
				// 状态查询
				Predicate[] p = new Predicate[list.size()];
				return criteriaBuilder.and(list.toArray(p));
			}
		};
		Page<PredictDataEntity>  page = dao.findAll(specifications, pageable);
		return page;
	}
}
